<template>
  <el-dialog :model-value="visible" @close="$emit('update:visible', false)" width="420px" :title="expert && expert.id ? '编辑专家' : '新增专家'">
    <el-form :model="form" label-width="72px" class="pt-2">
      <el-form-item label="姓名" required>
        <el-input v-model="form.name" maxlength="20" />
      </el-form-item>
      <el-form-item label="领域" required>
        <el-select v-model="form.field" multiple filterable allow-create default-first-option placeholder="请选择领域" style="width:100%" :collapse-tags="true">
          <el-option v-for="item in fields" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="单位" required>
        <el-input v-model="form.org" maxlength="30" />
      </el-form-item>
      <el-form-item label="职称" required>
        <el-input v-model="form.title" maxlength="20" />
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input v-model="form.contact" maxlength="30" />
      </el-form-item>
      <el-form-item label="简介">
        <el-input v-model="form.intro" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="请输入专家简介（最多500字）" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="$emit('update:visible', false)">取消</el-button>
      <el-button type="primary" @click="onSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
const mockFields = [
  '飞行安全管理',
  '飞行技术与操作',
  '航空器维修与工程',
  '空中交通管制',
  '适航审定与认证',
  '航空气象服务',
  '航空医学与健康',
  '航空法律法规',
  '航空运营管理',
  '航空人才培养',
  '航空应急救援',
  '航空运输规划',
  '航空电子系统',
  '航空材料工程',
  '航空制造工程'
]
const props = defineProps({
  visible: Boolean,
  expert: Object,
  fields: Array,
  orgs: Array,
})
const emit = defineEmits(['update:visible', 'save'])
const form = ref({
  name: '',
  field: [],
  org: '',
  title: '',
  contact: '',
  intro: '',
})
const fields = computed(() => (props.fields && props.fields.length ? props.fields : mockFields))
watch(() => props.expert, val => {
  if (val) {
    form.value = {
      name: val.name || '',
      field: Array.isArray(val.field) ? val.field : (val.field ? val.field.split(/[，,\s]+/).filter(Boolean) : []),
      org: val.org || '',
      title: val.title || '',
      contact: val.contact || '',
      intro: val.intro || '',
    }
  } else {
    form.value = { name: '', field: [], org: '', title: '', contact: '', intro: '' }
  }
}, { immediate: true })
function onSave() {
  const data = { ...form.value, field: form.value.field.join(',') }
  emit('save', data)
}
</script>

<style scoped>
.el-form {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px 0 0 0;
}
</style> 